package com.nebula.controller.management;

import com.alibaba.fastjson.JSON;
import com.nebula.controller.BaseController;
import com.nebula.entity.RoleNavigation;
import com.nebula.common.Const;
import com.nebula.common.Result;
import com.nebula.service.IRoleNavigationService;
import com.nebula.service.IUserService;
import com.nebula.service.impl.RoleNavigationServiceImpl;
import com.nebula.service.impl.UserServiceImpl;
import com.nebula.vo.UserVo;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author CcccX
 * @since 2020-08-07 22:18
 */
@WebServlet(name = "RoleSettingController", urlPatterns = "/manage/roleSetting")
public class RoleSettingController extends BaseController {

    private final IRoleNavigationService roleNavigationService = new RoleNavigationServiceImpl();

    public String index(HttpServletRequest request, HttpServletResponse response) {
        String navId = request.getParameter("id");
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        IUserService userService = new UserServiceImpl();
        if (userService.checkNavRole(user.getRoleId(), navId)) {
            return Const.FORWARD + Const.DEFAULT_URL + "website/role-setting.jsp";
        } else {
            return Const.FORWARD + "role-error.jsp";
        }
    }

    public String save(HttpServletRequest request, HttpServletResponse response) {
        String roleId = request.getParameter("roleId");
        String checkedNodes = request.getParameter("navIds");

        final String SPLIT = ",";

        if (StringUtils.isBlank(roleId)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("非法请求"));
        }

        if (StringUtils.isBlank(checkedNodes)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("角色权限不能为空"));
        }

        if (SPLIT.endsWith(checkedNodes)) {
            checkedNodes = checkedNodes.substring(0, checkedNodes.length() - 1);
        }

        String[] navIds = checkedNodes.split(SPLIT);

        //删除角色下的所有权限
        roleNavigationService.deleteByRoleId(Integer.parseInt(roleId));

        List<RoleNavigation> roleNavigations = new ArrayList<>();
        for (String navId : navIds) {
            RoleNavigation roleNavigation = new RoleNavigation();
            roleNavigation.setRoleId(Integer.parseInt(roleId));
            roleNavigation.setNavId(navId);
            roleNavigations.add(roleNavigation);
        }

        int resultCount = roleNavigationService.save(roleNavigations);

        if (resultCount <= 0) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage(Const.PROGRAM_EXCEPTION));
        }

        return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("保存成功"));
    }
}
